<template>

  <div class="mall-container">
    <!-- 顶部导航栏 -->
    <header class="mall-header">
      <div class="container">
        <div class="header-content">
          <!-- 商城Logo -->
          <div class="logo">
            <h1 class="logo-text">手机<span>商城</span></h1>
          </div>

          <!-- 搜索框 -->
          <div class="search-box">
            <input
                type="text"
                placeholder="搜索商品..."
                class="search-input"
                v-model="keyword"
                @keyup.enter="searchProducts"
            >
            <button class="search-button" @click="searchProducts">
              <i class="fa fa-search"></i>
            </button>
          </div>

          <!-- 用户操作区 -->
          <div class="user-actions">
            <button
                class="action-button login-button"
                @click="goToLogin"
                title="登录/注册"
            >
              <i class="fa fa-user-circle"></i>
            </button>
          </div>
        </div>
      </div>
    </header>

    <!--头部-->
    <header-component/>

    <!-- 主内容区 -->
    <main class="mall-main">
      <div class="container">
        <div class="main-content">
          <!-- 分类列表 -->
          <aside class="categories">
            <h2 class="categories-title" @click="filterByCategory(null)">商品分类</h2>
            <ul class="categories-list">
              <li
                  v-for="category in categories"
                  :key="category.categoryId"
                  :class="{ 'active': activeCategory === category.categoryId }"
                  @click="filterByCategory(category.categoryId)"
              >
                <span>{{ category.categoryName }}</span>
              </li>
            </ul>
          </aside>

          <!-- 商品展示区 -->
          <section class="products">
            <div class="products-header">
              <h2 class="products-title">
                {{ activeCategoryName }}
                <span class="products-count">({{ filteredProducts.length }})</span>
              </h2>
              <div class="sort-options">
                <span>排序:</span>
                <select v-model="sortOption" @change="sortProducts">
                  <option value="default">默认</option>
                  <option value="price-asc">价格从低到高</option>
                  <option value="price-desc">价格从高到低</option>
                  <option value="stock-asc">库存从少到多</option>
                  <option value="stock-desc">库存从多到少</option>
                </select>
              </div>
            </div>

            <!-- 商品网格 -->
            <div class="products-grid">
              <div
                  v-for="product in filteredProducts"
                  :key="product.productId"
                  class="product-card"
                  @mouseenter="productHovered = product.productId"
                  @mouseleave="productHovered = null"
              >

                <div class="product-image">
                  <img
                      :src="product.image"
                      :alt="product.productName"
                      class="product-img"
                  >
                  <div class="quick-actions">
                    <button
                        class="action-btn"
                        @click="addToCart(product)"
                        title="加入购物车"
                    >
                      <i class="fa fa-shopping-cart"></i>
                    </button>
                    <button
                        class="action-btn"
                        @click="buyNow(product)"
                        title="立即购买"
                    >
                      <i class="fa fa-bolt"></i>
                    </button>
                  </div>
                </div>
                <div class="product-info">
                  <h3 class="product-name">{{ product.productName }}</h3>
                  <div class="product-details">
                    <div class="product-price">
                      <span class="currency">¥</span>
                      <span class="price-value">{{ product.price.toFixed(2) }}</span>
                    </div>
                    <div class="product-stock">
                      <i class="fa fa-box"></i>
                      <span>{{ product.stock }} 件</span>
                    </div>
                  </div>
                  <div class="product-actions">
                    <button
                        class="btn add-to-cart-btn"
                        @click="addToCart(product)"
                    >
                      <i class="fa fa-shopping-cart"></i>
                      <span>加入购物车</span>
                    </button>
                    <button
                        class="btn buy-now-btn"
                        @click="buyNow(product)"
                    >
                      <i class="fa fa-bolt"></i>
                      <span>立即购买</span>
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 无商品提示 -->
            <div v-if="filteredProducts.length === 0" class="no-products">
              <i class="fa fa-search"></i>
              <p>没有找到相关商品，请尝试其他搜索条件</p>
            </div>
          </section>
        </div>
      </div>
    </main>
<!--    &lt;!&ndash;引入底部导航栏&ndash;&gt;-->
<!--    <foot-component-->
<!--        :cart-count="cartCount"-->
<!--        :current-path="$route.path"-->
<!--        @navigate="handleNavigate"-->
<!--    />-->

<!--    尾部-->
    <tailder-component/>
<!--    <header-component/>-->
  </div>
</template>

<script>
import axios from 'axios';
import HeaderComponent  from "@/components/HeaderComponent.vue";
import  TailderComponent from "@/components/TailderComponent.vue";
// import FootComponent from "@/components/product/FootComponent";

export default {
  name: 'HomeView',
  data() {
    return {
      keyword: '', // 搜索词
      activeCategory: null,
      activeCategoryName: '热门商品',
      sortOption: 'default',
      productHovered: null,
      categories: [], // 商品分类列表
      products: [],
      // cartCount: '' // 购物车数量
    };
  },
  computed: {
    // 过滤后的商品列表
    filteredProducts() {
      // 先按分类过滤
      let filtered = this.activeCategory
          ? this.products.filter(product => product.categoryId === this.activeCategory)
          : this.products;
      // 再按搜索词过滤
      if (this.keyword.trim()) {
        const query = this.keyword.toLowerCase().trim();
        filtered = filtered.filter(product =>
            product.productName.toLowerCase().includes(query)
        );
      }
      // 最后按排序选项排序
      filtered = this.sortProducts(filtered);
      return filtered;
    }
  },
  methods: {
    // 所有分类列表
    allCategories() {
      axios.get('/api/category/all')
          .then(response => {
            console.log('获取所有分类成功:', response.data);
            console.log(response.data);

            this.categories = response.data;
          })
          .catch(error => {
            console.error(error);
          });
    },
    // 跳转到登录页面
    goToLogin() {
      console.log('跳转到登录页面');
      this.$router.push('/login');
    },
    // // 处理底部导航点击事件
    // handleNavigate(path) {
    //   //要求不要跳转到当前页面
    //   if (this.$route.path === path) {
    //     return;
    //   }
    //   this.$router.push(path);
    // },
    // 搜索商品
    searchProducts() {
      axios.get('/api/product/searchByKeyword/'+this.keyword)
          .then(response => {
            this.products = response.data;
            this.activeCategoryName = '搜索到的商品';
          })
          .catch(error => {
            console.error('搜索出错:', error);
          });
    },
    //获取所有商品
    allProducts() {
      axios.get('/api/product/hot').then(response => {
        console.log('获取热门商品成功:', response.data);
        this.products = response.data;
      }).catch(error => {
        console.error('获取商品出错:', error);
      })
    },
    // 按分类筛选商品
    filterByCategory(categoryId) {
      this.activeCategory = categoryId;
      if (this.activeCategory === null){
        this.activeCategoryName = '热门商品';
        //获取热门商品
        this.allProducts();
      }else {
        axios.get('/api/product/searchByCategory/'+categoryId).then(response => {
          this.products = response.data;
          this.activeCategoryName = this.categories.find(category => category.categoryId === categoryId).categoryName;
        }).catch(error => {
          console.error('获取商品出错:', error);
        })
      }
    },

    // 排序商品
    sortProducts(products = null) {
      const items = products || [...this.products]; // 使用原始商品列表排序

      switch (this.sortOption) {
        case 'price-asc':
          return items.sort((a, b) => a.price - b.price);
        case 'price-desc':
          return items.sort((a, b) => b.price - a.price);
        case 'stock-asc':
          return items.sort((a, b) => a.stock - b.stock);
        case 'stock-desc':
          return items.sort((a, b) => b.stock - a.stock);
        default:
          return items;
      }
    },
    // //获取购物车数量
    // async getCartCount() {
    //   try {
    //     const response = await axios.get('/api/cart/getCartCount');
    //     this.cartCount = response.data;
    //   } catch (error) {
    //     console.error('获取购物车数量失败:', error);
    //   }
    // },
    // 添加商品到购物车
    addToCart(product) {
      axios.post('/api/cart/add/' + product.productId).then(response => {
         console.log('添加到购物车成功:', response.data);
      }).catch(error => {
        console.error('添加到购物车出错:', error);
      });
      this.cartCount++; // 购物车数量加1
    },

    // 立即购买
    buyNow(product) {
      axios.get('/api/order/buyOne/' + product.productId).then(response => {
        console.log('下单成功:', response.data);
      }).catch(error => {
        console.error('下单出错:', error);
      });
      console.log(`立即购买: ${product.productName}`);
      // 在实际项目中，这里应该跳转到结算页面
      alert(`即将购买: ${product.productName}`);
    }
  },
  mounted() {
    // 页面加载时的初始化操作
    console.log('商城主页加载完成');
    this.allCategories();
    this.allProducts();
    this.getCartCount();
  },
  components: {
    // FootComponent,
    HeaderComponent,
    TailderComponent
  }
};
</script>

<style scoped>
/* 全局样式 */
:root {
  --primary-color: #7af6fa; /* 浅蓝色 - 主色调 */
  --secondary-color: #ffc0cb; /* 浅粉色 - 辅助色 */
  --success-color: #10b981;
  --warning-color: #61eaf6;
  --danger-color: #ef4444;
  --dark-color: #1e293b;
  --light-color: #f8fafc;
  --gray-color: #94a3b8;
  --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  --card-hover-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Inter', system-ui, sans-serif;
  line-height: 1.6;
  color: var(--dark-color);
  background-color: var(--light-color);
}

.container {
  /*max-width: 1200px;*/
  margin: 0 auto;
  padding: 0 15px;
}

/* 顶部导航栏样式 */
.mall-header {
  background-color: white;
  width: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80px;
}

.logo .logo-text {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--primary-color);
}

.logo .logo-text span {
  color: var(--secondary-color);
}

.search-box {
  display: flex;
  flex: 1;
  max-width: 500px;
  margin: 0 20px;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 4px 0 0 4px;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: var(--primary-color);
}

.search-button {
  padding: 10px 15px;
  background-color: #4fb9f5;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #4fb9f5;
}

.user-actions {
  display: flex;
  gap: 15px;
}

.action-button {
  position: relative;
  width: 50px;
  height: 50px;
  background-color: #7adbfa;
  border: none;
  border-radius: 50%;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-button i {
  font-size: 1.5rem; /* 增大图标字体大小 */
}

.action-button:hover {
  background-color: #4fb9f5;
  transform: scale(1.1); /* 鼠标悬停时稍微放大 */
}

/* 主内容区样式 */
.mall-main {
  padding: 30px 0;
  margin-bottom: 60px; /* 为底部导航栏留出空间 */
}

.main-content {
  display: flex;
  gap: 30px;
}

/* 分类列表样式 */
.categories {
  flex: 0 0 220px;
  background-color: white;
  border-radius: 8px;
  box-shadow: var(--card-shadow);
  padding: 20px;
}

.categories-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 15px;
  color: var(--dark-color);
  padding-bottom: 10px;
  border-bottom: 1px solid #f1f5f9;
}

.categories-list {
  list-style: none;
}

.categories-list li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--dark-color);
}

.categories-list li:hover {
  background-color: #f1f5f9;
  color: var(--primary-color);
}

.categories-list li.active {
  background-color: rgba(122, 219, 250, 0.2);
  color: var(--primary-color);
  font-weight: 500;
}

/* 商品展示区样式 */
.products {
  flex: 1;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.products-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--dark-color);
}

.products-count {
  font-size: 0.9rem;
  color: var(--gray-color);
  font-weight: normal;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sort-options select {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 0.9rem;
  outline: none;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s;
}

.sort-options select:focus {
  border-color: var(--primary-color);
}

/* 商品网格样式 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
}

.product-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: var(--card-shadow);
  overflow: hidden;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.product-card:hover {
  box-shadow: var(--card-hover-shadow);
  transform: translateY(-5px);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.product-card:hover .product-img {
  transform: scale(1.05);
}

.quick-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  opacity: 0;
  transform: translateX(20px);
  transition: all 0.3s ease;
}

.product-card:hover .quick-actions {
  opacity: 1;
  transform: translateX(0);
}

.action-btn {
  width: 32px;
  height: 32px;
  background-color: var(--primary-color);
  color: var(--dark-color);
  border: none;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.action-btn:hover {
  background-color: var(--primary-color);
  color: white;
}

.product-info {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--dark-color);
  margin-bottom: 10px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.product-price {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 0.9rem;
  color: var(--gray-color);
  margin-right: 2px;
}

.price-value {
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--dark-color);
}

.product-stock {
  display: flex;
  align-items: center;
  color: var(--gray-color);
  font-size: 0.9rem;
}

.product-stock i {
  margin-right: 5px;
}

.product-actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.add-to-cart-btn {
  background-color: #7ADBFAFF; /* 浅蓝色 - 加入购物车按钮 */
  color: white;
}

.add-to-cart-btn:hover {
  background-color: #4fb9f5;
}

.buy-now-btn {
  background-color: #FFC0CBFF; /* 浅粉色 - 立即购买按钮 */
  color: white;
}

.buy-now-btn:hover {
  background-color: #ff9bb3;
}

.no-products {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  text-align: center;
  color: var(--gray-color);
}

.no-products i {
  font-size: 48px;
  margin-bottom: 20px;
  opacity: 0.5;
}

/* 底部导航栏样式 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 0;
  z-index: 99;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--gray-color);
  cursor: pointer;
  padding: 8px 0;
  position: relative;
}

.nav-item.active {
  color: var(--primary-color);
}

.nav-item i {
  font-size: 1.5rem;
  margin-bottom: 4px;
}

.nav-item span {
  font-size: 0.75rem;
}

.cart-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: var(--secondary-color);
  color: white;
  font-size: 0.6rem;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 页脚样式 */
.mall-footer {
  background-color: white;
  border-top: 1px solid #f1f5f9;
  padding: 40px 0;
  margin-top: 50px;
}

.footer-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
}

.footer-section h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--dark-color);
  margin-bottom: 15px;
}

.footer-section ul {
  list-style: none;
}

.footer-section ul li {
  margin-bottom: 10px;
}

.footer-section ul li a {
  color: var(--gray-color);
  text-decoration: none;
  transition: color 0.3s;
}

.footer-section ul li a:hover {
  color: var(--primary-color);
}

.social-icons {
  display: flex;
  gap: 15px;
}

.social-icon {
  width: 36px;
  height: 36px;
  background-color: #f1f5f9;
  color: var(--dark-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
  transition: all 0.3s;
}

.social-icon:hover {
  background-color: var(--primary-color);
  color: white;
}

.footer-bottom {
  border-top: 1px solid #f1f5f9;
  padding-top: 20px;
  text-align: center;
  color: var(--gray-color);
  font-size: 0.9rem;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }

  .categories {
    flex: 1;
    margin-bottom: 30px;
  }

  .categories-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .categories-list li {
    padding: 8px 12px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 15px 0;
  }

  .logo {
    margin-bottom: 15px;
  }

  .search-box {
    max-width: 100%;
    margin: 0 0 15px 0;
  }

  .products-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }

  .footer-content {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}

@media (max-width: 576px) {
  .products-grid {
    grid-template-columns: 1fr;
  }

  .footer-content {
    grid-template-columns: 1fr;
  }
}
</style>